﻿/*
    Copyright (c) 2012, iD Commerce + Logistics
    All rights reserved.

    Redistribution and use in source and binary forms, with or without modification, are permitted
    provided that the following conditions are met:

    Redistributions of source code must retain the above copyright notice, this list of conditions
    and the following disclaimer. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the documentation and/or other
    materials provided with the distribution.
 
    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
    IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
    FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
    OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity.Core;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace IdComLog.EntityFramework
{
    /// <summary>
    /// Extension methods for ObjectContext and DbContext
    /// </summary>
    public static class DbContextExtensions
    {
        /// <summary>
        /// Retries updates if there are optimistic concurrency exceptions.
        /// </summary>
        /// <param name="ctx">The context to update on.</param>
        /// <param name="mode">Determines how offending entities should be handled when an optimistic concurrency exception occurs.</param>
        /// <param name="tries">The number of retries until it gives up.</param>
        /// <param name="action">The action which performs database updates.</param>
        public static void RetryUpdates(this IObjectContextAdapter ctx, RefreshMode mode, int tries, Action action)
        {
            if (ctx == null) throw new ArgumentNullException("ctx");
            if (tries <= 0) throw new ArgumentOutOfRangeException("tries");
            if (action == null) throw new ArgumentNullException("action");

            RetryUpdates(ctx.ObjectContext, mode, tries, action);
        }

        /// <summary>
        /// Retries updates if there are optimistic concurrency exceptions.
        /// </summary>
        /// <param name="ctx">The context to update on.</param>
        /// <param name="mode">Determines how offending entities should be handled when an optimistic concurrency exception occurs.</param>
        /// <param name="tries">The number of retries until it gives up.</param>
        /// <param name="action">The action which performs database updates.</param>
        public static void RetryUpdates(this ObjectContext ctx, RefreshMode mode, int tries, Action action)
        {
            if (ctx == null) throw new ArgumentNullException("ctx");
            if (tries <= 0) throw new ArgumentOutOfRangeException("tries");
            if (action == null) throw new ArgumentNullException("action");

            int sleepTime = 50;

            while (true)
            {
                bool shouldSleep = false;

                try
                {
                    action();
                    return;
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    if (tries-- == 0) throw;
                    ctx.Refresh(mode, ex.Entries.Select(x => x.Entity));
                }
                catch (OptimisticConcurrencyException ex)
                {
                    if (tries-- == 0) throw;
                    ctx.Refresh(mode, ex.StateEntries.Select(x => x.Entity));
                }
                catch (Exception ex)
                {
                    if (tries-- == 0 || !ex.IsDeadlock())
                        throw;

                    shouldSleep = true;
                }

                if (shouldSleep)
                {
                    Thread.Sleep(sleepTime);
                    sleepTime = sleepTime + sleepTime / 2;
                }
            }
        }

        /// <summary>
        /// Retries updates if there are optimistic concurrency exceptions.
        /// </summary>
        /// <param name="ctx">The context to update on.</param>
        /// <param name="mode">Determines how offending entities should be handled when an optimistic concurrency exception occurs.</param>
        /// <param name="tries">The number of retries until it gives up.</param>
        /// <param name="action">The action which performs database updates.</param>
        /// <returns>The value returned by the most recent call to <paramref name="action"/>.</returns>
        public static TResult RetryUpdates<TResult>(this IObjectContextAdapter ctx, RefreshMode mode, int tries, Func<TResult> action)
        {
            if (ctx == null) throw new ArgumentNullException("ctx");
            if (tries <= 0) throw new ArgumentOutOfRangeException("tries");
            if (action == null) throw new ArgumentNullException("action");

            return RetryUpdates(ctx.ObjectContext, mode, tries, action);
        }

        /// <summary>
        /// Retries updates if there are optimistic concurrency exceptions.
        /// </summary>
        /// <param name="ctx">The context to update on.</param>
        /// <param name="mode">Determines how offending entities should be handled when an optimistic concurrency exception occurs.</param>
        /// <param name="tries">The number of retries until it gives up.</param>
        /// <param name="action">The action which performs database updates.</param>
        /// <returns>The value returned by the most recent call to <paramref name="action"/>.</returns>
        public static TResult RetryUpdates<TResult>(this ObjectContext ctx, RefreshMode mode, int tries, Func<TResult> action)
        {
            if (ctx == null) throw new ArgumentNullException("ctx");
            if (tries <= 0) throw new ArgumentOutOfRangeException("tries");
            if (action == null) throw new ArgumentNullException("action");

            int sleepTime = 50;

            while(true)
            {
                bool shouldSleep = false;

                try
                {
                    return action();
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    if (tries-- == 0) throw;
                    ctx.Refresh(mode, ex.Entries.Select(x => x.Entity));
                }
                catch (OptimisticConcurrencyException ex)
                {
                    if (tries-- == 0) throw;
                    ctx.Refresh(mode, ex.StateEntries.Select(x => x.Entity));
                }
                catch (Exception ex)
                {
                    if (tries-- == 0 || !ex.IsDeadlock())
                        throw;

                    shouldSleep = true;
                }

                if (shouldSleep)
                {
                    Thread.Sleep(sleepTime);
                    sleepTime = sleepTime + sleepTime / 2;
                }
            }
        }

        /// <summary>
        /// Retries updates if there are optimistic concurrency exceptions.
        /// </summary>
        /// <param name="ctx">The context to update on.</param>
        /// <param name="mode">Determines how offending entities should be handled when an optimistic concurrency exception occurs.</param>
        /// <param name="tries">The number of retries until it gives up.</param>
        /// <param name="action">The action which performs database updates.</param>
        /// <param name="token">A token used for cancellation of the asynchronous operation.</param>
        /// <returns>A task representing the asynchronous update operation.</returns>
        public static Task RetryUpdates(this IObjectContextAdapter ctx, RefreshMode mode, int tries, Func<CancellationToken, Task> action, CancellationToken token)
        {
            if (ctx == null) throw new ArgumentNullException("ctx");
            if (tries <= 0) throw new ArgumentOutOfRangeException("tries");
            if (action == null) throw new ArgumentNullException("action");

            return RetryUpdates(ctx.ObjectContext, mode, tries, action, token);
        }

        /// <summary>
        /// Retries updates if there are optimistic concurrency exceptions.
        /// </summary>
        /// <param name="ctx">The context to update on.</param>
        /// <param name="mode">Determines how offending entities should be handled when an optimistic concurrency exception occurs.</param>
        /// <param name="tries">The number of retries until it gives up.</param>
        /// <param name="action">The action which performs database updates.</param>
        /// <param name="token">A token used for cancellation of the asynchronous operation.</param>
        /// <returns>A task representing the asynchronous update operation.</returns>
        public static async Task RetryUpdates(this ObjectContext ctx, RefreshMode mode, int tries, Func<CancellationToken, Task> action, CancellationToken token)
        {
            if (ctx == null) throw new ArgumentNullException("ctx");
            if (tries <= 0) throw new ArgumentOutOfRangeException("tries");
            if (action == null) throw new ArgumentNullException("action");

            int sleepTime = 50;

            while (true)
            {
                IEnumerable<object> refreshEntities = null;
                bool shouldSleep = false;

                try
                {
                    await action(token);
                    return;
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    if (tries-- == 0) throw;
                    refreshEntities = ex.Entries.Select(x => x.Entity);
                }
                catch (OptimisticConcurrencyException ex)
                {
                    if (tries-- == 0) throw;
                    refreshEntities = ex.StateEntries.Select(x => x.Entity);
                }
                catch (Exception ex)
                {
                    if (tries-- == 0 || !ex.IsDeadlock())
                        throw;

                    shouldSleep = true;
                }

                if (refreshEntities != null)
                {
                    await ctx.RefreshAsync(mode, refreshEntities, token);
                }

                if (shouldSleep)
                {
                    await Task.Delay(sleepTime, token);
                    sleepTime = sleepTime + sleepTime / 2;
                }
            }
        }

        /// <summary>
        /// Retries updates if there are optimistic concurrency exceptions.
        /// </summary>
        /// <param name="ctx">The context to update on.</param>
        /// <param name="mode">Determines how offending entities should be handled when an optimistic concurrency exception occurs.</param>
        /// <param name="tries">The number of retries until it gives up.</param>
        /// <param name="action">The action which performs database updates.</param>
        /// <param name="token">A token used for cancellation of the asynchronous operation.</param>
        /// <returns>The value returned by the most recent call to <paramref name="action"/>.</returns>
        public static Task<TResult> RetryUpdates<TResult>(this IObjectContextAdapter ctx, RefreshMode mode, int tries, Func<CancellationToken, Task<TResult>> action, CancellationToken token)
        {
            if (ctx == null) throw new ArgumentNullException("ctx");
            if (tries <= 0) throw new ArgumentOutOfRangeException("tries");
            if (action == null) throw new ArgumentNullException("action");

            return RetryUpdates(ctx.ObjectContext, mode, tries, action, token);
        }

        /// <summary>
        /// Retries updates if there are optimistic concurrency exceptions.
        /// </summary>
        /// <param name="ctx">The context to update on.</param>
        /// <param name="mode">Determines how offending entities should be handled when an optimistic concurrency exception occurs.</param>
        /// <param name="tries">The number of retries until it gives up.</param>
        /// <param name="action">The action which performs database updates.</param>
        /// <param name="token">A token used for cancellation of the asynchronous operation.</param>
        /// <returns>The value returned by the most recent call to <paramref name="action"/>.</returns>
        public static async Task<TResult> RetryUpdates<TResult>(this ObjectContext ctx, RefreshMode mode, int tries, Func<CancellationToken, Task<TResult>> action, CancellationToken token)
        {
            if (ctx == null) throw new ArgumentNullException("ctx");
            if (tries <= 0) throw new ArgumentOutOfRangeException("tries");
            if (action == null) throw new ArgumentNullException("action");

            int sleepTime = 50;

            while (true)
            {
                IEnumerable<object> refreshEntities = null;
                bool shouldSleep = false;

                try
                {
                    return await action(token);
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    if (tries-- == 0) throw;
                    refreshEntities = ex.Entries.Select(x => x.Entity);
                }
                catch (OptimisticConcurrencyException ex)
                {
                    if (tries-- == 0) throw;
                    refreshEntities = ex.StateEntries.Select(x => x.Entity);
                }
                catch (Exception ex)
                {
                    if (tries-- == 0 || !ex.IsDeadlock())
                        throw;

                    shouldSleep = true;
                }

                if (refreshEntities != null)
                {
                    await ctx.RefreshAsync(mode, refreshEntities, token);
                }

                if (shouldSleep)
                {
                    await Task.Delay(sleepTime, token);
                    sleepTime = sleepTime + sleepTime / 2;
                }
            }
        }

        /// <summary>
        /// Retries updates if there are optimistic concurrency exceptions.
        /// </summary>
        /// <param name="ctx">The context to update on.</param>
        /// <param name="tries">The number of retries until it gives up.</param>
        /// <param name="action">The action which performs database updates.</param>
        /// <returns>The value returned by the most recent call to <paramref name="action"/>.</returns>
        public static TResult RetryDeadlocks<TResult>(this IObjectContextAdapter ctx, int tries, Func<TResult> action)
        {
            if (ctx == null) throw new ArgumentNullException("ctx");
            if (tries <= 0) throw new ArgumentOutOfRangeException("tries");
            if (action == null) throw new ArgumentNullException("action");
            return RetryDeadlocks(ctx.ObjectContext, tries, action);
        }

        /// <summary>
        /// Retries updates if there are optimistic concurrency exceptions.
        /// </summary>
        /// <param name="ctx">The context to update on.</param>
        /// <param name="tries">The number of retries until it gives up.</param>
        /// <param name="action">The action which performs database updates.</param>
        /// <returns>The value returned by the most recent call to <paramref name="action"/>.</returns>
        public static TResult RetryDeadlocks<TResult>(this ObjectContext ctx, int tries, Func<TResult> action)
        {
            if (ctx == null) throw new ArgumentNullException("ctx");
            if (tries <= 0) throw new ArgumentOutOfRangeException("tries");
            if (action == null) throw new ArgumentNullException("action");

            int sleepTime = 50;

            while (true)
            {
                try
                {
                    return action();
                }
                catch (Exception ex)
                {
                    if (tries-- == 0 || !ex.IsDeadlock())
                        throw;
                }

                Thread.Sleep(sleepTime);
                sleepTime = sleepTime + sleepTime / 2;
            }
        }

        /// <summary>
        /// Retries queries if there are any deadlock exceptions.
        /// </summary>
        /// <param name="ctx">The context to query on.</param>
        /// <param name="tries">The number of retries until it gives up.</param>
        /// <param name="action">The action which performs database queries.</param>
        /// <param name="token">A token used for cancellation of the asynchronous operation.</param>
        /// <returns>The value returned by the most recent call to <paramref name="action"/>.</returns>
        public static Task<TResult> RetryDeadlocks<TResult>(this IObjectContextAdapter ctx, int tries, Func<CancellationToken, Task<TResult>> action, CancellationToken token)
        {
            if (ctx == null) throw new ArgumentNullException("ctx");
            if (tries <= 0) throw new ArgumentOutOfRangeException("tries");
            if (action == null) throw new ArgumentNullException("action");

            return RetryDeadlocks(ctx.ObjectContext, tries, action, token);
        }

        /// <summary>
        /// Retries queries if there are any deadlock exceptions.
        /// </summary>
        /// <param name="ctx">The context to query on.</param>
        /// <param name="tries">The number of retries until it gives up.</param>
        /// <param name="action">The action which performs database queries.</param>
        /// <param name="token">A token used for cancellation of the asynchronous operation.</param>
        /// <returns>The value returned by the most recent call to <paramref name="action"/>.</returns>
        public static async Task<TResult> RetryDeadlocks<TResult>(this ObjectContext ctx, int tries, Func<CancellationToken, Task<TResult>> action, CancellationToken token)
        {
            if (ctx == null) throw new ArgumentNullException("ctx");
            if (tries <= 0) throw new ArgumentOutOfRangeException("tries");
            if (action == null) throw new ArgumentNullException("action");

            int sleepTime = 50;

            while (true)
            {
                try
                {
                    return await action(token);
                }
                catch (Exception ex)
                {
                    if (tries-- == 0 || !ex.IsDeadlock())
                        throw;
                }

                await Task.Delay(sleepTime, token);
                sleepTime = sleepTime + sleepTime / 2;
            }
        }

        static bool IsDeadlock(this Exception ex)
        {
            Debug.Assert(ex != null);

            if ((ex is EntityCommandExecutionException || ex is DbUpdateException) == false)
            {
                return false;
            }

            do
            {
                if (ex.Message.IndexOf("deadlocked", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    return true;
                }

                ex = ex.InnerException;
            }
            while (ex != null);

            return false;
        }
    }
}
